'use client';

import { useState, useEffect } from 'react';
import Image from 'next/image';
import axios from 'axios';

interface Message {
  id: number;
  sender: string;
  content: string;
  timestamp: string;
  avatar: string;
}

export default function ChatList() {
  const [messages, setMessages] = useState<Message[]>([]);
  const [error, setError] = useState<string>('');
  const [editingId, setEditingId] = useState<number | null>(null);
  const [editContent, setEditContent] = useState('');

  // 获取所有消息
  const fetchMessages = async () => {
    try {
      const response = await axios.get('/api/messages');
      setMessages(response.data);
    } catch (err) {
      console.error('获取消息失败:', err);
      setError('获取消息失败');
    }
  };

  // 初始加载
  useEffect(() => {
    fetchMessages();
  }, []);

  // 添加新消息
  const addMessage = async (sender: string, content: string) => {
    try {
      const response = await axios.post('/api/messages', { sender, content });
      setMessages([response.data, ...messages]);
    } catch (err) {
      console.error('发送消息失败:', err);
      setError('发送消息失败');
    }
  };

  // 更新消息
  const updateMessage = async (id: number, content: string) => {
    try {
      const response = await axios.put('/api/messages', { id, content });
      setMessages(messages.map(msg =>
        msg.id === id ? response.data : msg
      ));
      setEditingId(null);
      setEditContent('');
    } catch (err) {
      console.error('更新消息失败:', err);
      setError('更新消息失败');
    }
  };

  // 删除消息
  const deleteMessage = async (id: number) => {
    try {
      await axios.delete('/api/messages', { data: { id } });
      setMessages(messages.filter(msg => msg.id !== id));
    } catch (err) {
      console.error('删除消息失败:', err);
      setError('删除消息失败');
    }
  };

  // 模拟数据用于测试
  const mockData = [
    {
      id: 1,
      sender: '张工',
      content: '早上好！今天的会议准备得怎么样了？',
      timestamp: '08:30',
      avatar: 'https://xinglong.tech/assets/logo-DVj_ONTu.jpg'
    },
    {
      id: 2,
      sender: '李经理',
      content: '已经准备好了，PPT我昨晚修改完成，等下发给你review一下。',
      timestamp: '08:32',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Li'
    },
    {
      id: 3,
      sender: '小王',
      content: '大家早啊！今天天气真不错。',
      timestamp: '08:35',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Wang'
    },
    {
      id: 37,
      sender: '运维 - 老张',
      content: '备份系统已经升级完成，数据安全性得到提升。',
      timestamp: '11:10',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=LaoZhang'
    },
    {
      id: 38,
      sender: '人事部 - 周姐',
      content: '年度培训计划已经制定好了，即将开始报名。',
      timestamp: '11:15',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Zhou'
    },
    {
      id: 39,
      sender: '前端 - 老王',
      content: '代码重构完成，项目结构更清晰了。',
      timestamp: '11:20',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=LaoWang'
    },
    {
      id: 40,
      sender: '后端 - 张三',
      content: '数据迁移方案已经制定好了，周末准备执行。',
      timestamp: '11:25',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=ZhangSan'
    },
    {
      id: 41,
      sender: '市场部 - 陈总',
      content: '新的营销活动效果不错，用户反馈很积极。',
      timestamp: '11:30',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Chen'
    },
    {
      id: 42,
      sender: 'UI设计 - 小美',
      content: '新的动效设计已经完成，增加了用户体验。',
      timestamp: '11:35',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Mei'
    },
    {
      id: 43,
      sender: '测试 - 李四',
      content: '安全测试报告已经出来了，需要修复几个漏洞。',
      timestamp: '11:40',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=LiSi'
    },
    {
      id: 44,
      sender: '运维 - 王五',
      content: '负载均衡配置已经优化完成，系统更稳定了。',
      timestamp: '11:45',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=WangWu'
    },
    {
      id: 45,
      sender: '产品经理 - 赵工',
      content: '竞品分析报告已经完成，下午讨论一下。',
      timestamp: '11:50',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Zhao'
    },
    {
      id: 46,
      sender: '前端 - 小张',
      content: '新的动画效果已经实现，等待设计确认。',
      timestamp: '11:55',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=XiaoZhang'
    },
    {
      id: 47,
      sender: '后端 - 老李',
      content: '接口性能优化完成，响应时间达到预期。',
      timestamp: '12:00',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=LaoLi'
    },
    {
      id: 48,
      sender: '财务 - 刘姐',
      content: '预算报告已经修改完成，请各部门确认。预算报告已经修改完成，请各部门确认。预算报告已经修改完成，请各部门确认。',
      timestamp: '12:05',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Liu'
    },
    {
      id: 49,
      sender: 'UI设计 - 小美',
      content: '移动端的视觉优化已经完成，可以验收了。',
      timestamp: '12:10',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=Mei'
    },
    {
      id: 50,
      sender: '测试 - 小王',
      content: '回归测试已经完成，系统可以准备发布了。回归测试已经完成，系统可以准备发布了。回归测试已经完成，系统可以准备发布了。回归测试已经完成，系统可以准备发布了。',
      timestamp: '12:15',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=XiaoWang'
    }
  ]
  // 用于测试的初始数据
  useEffect(() => {
    if (messages.length === 0) {
      // mockData.forEach(msg => addMessage(msg.sender, msg.content));
      for (const msg of mockData) {
        addMessage(msg.sender, msg.content);
        break;
      }
    }
  }, []);

  return (
    <div className="max-w-md mx-auto bg-white h-[500px] flex flex-col">
      <div className="border-b border-gray-200 px-4 py-3">
        <h1 className="text-lg font-medium text-gray-900">微信</h1>
      </div>
      {error && (
        <div className="px-4 py-2 bg-red-100 text-red-700 text-sm">
          {error}
        </div>
      )}
      <div className="flex-1 overflow-y-auto flex flex-col-reverse bg-[#f5f5f5]">
        {messages.map(message => (
          <div key={message.id} className="flex items-start px-4 py-2.5  cursor-pointer">
            <div className="flex-shrink-0 h-9 w-9 mr-2 relative">
              <Image
                src={message.avatar}
                alt={message.sender}
                fill
                sizes="36px"
                className="rounded-[4px] object-cover"
              />
            </div>
            <div className="flex-1 min-w-0">
              <div className="flex items-baseline" style={{ fontSize: '10px' }}>
                <h2 className="font-medium text-gray-500">
                  {message.sender}
                </h2>
                <span className=" pl-1 text-gray-500">{message.timestamp}</span>
              </div>
              <p className="text-sm text-gray-900 break-words whitespace-pre-wrap inline-block bg-[#95ec69] rounded-[3px] px-2 py-1">
                {message.content}
              </p>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}